from rest_framework import serializers
from .models import User
from django_redis import get_redis_connection
import re
from rest_framework_jwt.settings import api_settings


class CreateUserSerializer(serializers.ModelSerializer):

    # 定义模型外部字段,仅输入 ,因为id在ModelSerializer中已经指定,二username和moblie为双向
    # password我么重新自定时页是write_only,凡是指定为write_only,序列化时直接忽略
    password2 = serializers.CharField(label='确认密码', write_only=True)
    sms_code = serializers.CharField(label='短信验证码', write_only=True)
    allow = serializers.CharField(label='同意协议', write_only=True)
    token = serializers.CharField(label='登陆状态token' ,read_only=True)

    class Meta:
        model = User
        # 所有字段:'id','username','moblie','password','password2','sms_code0','allow
        # 以上这些字段,除了后三个,其余在ModelSerializer中都有定义,所以我们光定义后三个就行
        # 输入字段(writer_only):username','moblie','password','password2','sms_code0','allow
        # 输出字段(read_only):'id','username','moblie'
        fields = ['id', 'username', 'password', 'password2', 'sms_code', 'allow', 'token']

        # 在AbstractUser中参数给的太少了,fields字段无法修改,所以只能给username 和password额外指定参数
        extra_kwargs = {
            'username': {
                'min_length': 5,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许5-20个字符的用户名',
                    'max_length': '仅允许5-20个字符的用户名',
                }
            },
            'password': {
                'write_only': True,
                'min_length': 8,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许8-20个字符的密码',
                    'max_length': '仅允许8-20个字符的密码',
                }
            }
        }

    def validate_mobile(self, value):
        """验证手机号"""
        if not re.match(r'^1[3-9]\d{9}$', value):
            raise serializers.ValidationError('手机号格式错误')
        return value

    def validate_allow(self, value):
        """检验用户是否同意协议"""
        if value != 'true':
            raise serializers.ValidationError('请同意用户协议')
        return value

    def validate(self, data):
        # 判断两次密码
        if data['password'] != data['password2']:
            raise serializers.ValidationError('两次密码不一致')

        # 判断短信验证码
        redis_conn = get_redis_connection('verify_codes')
        mobile = data['mobile']
        real_sms_code = redis_conn.get('sms_%s' % mobile)
        if real_sms_code is None:
            raise serializers.ValidationError('无效的短信验证码')
        if data['sms_code'] != real_sms_code.decode():
            raise serializers.ValidationError('短信验证码错误')

        return data

    def create(self, validated_data):
        # 重写序列化器的create方法,因为有些字段不能默认往User里面储存,比如我们自己定义的三个write_only
        """
        :param validated_data: 经过教研之后的数据
        :return: User输出字段(read_only):'id','username','moblie'
        """
        # 删除掉我们不需要保存的三个数据,就是我们自己定义的那些没有在MODEL中定义的字段
        del validated_data['password2']
        del validated_data['sms_code']
        del validated_data['allow']

        # 自己实现保存数据到User
        user = User.objects.create(**validated_data)

        # 调用django的认证系统加密密码
        user.set_password(validated_data['password'])
        user.save()

        # 保存数据之后,响应注册结果之前
        # 使用JWT来进行状态保持,JWT必session更加的安全,代码为官网代码,纯属拷贝
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
        # 当前注册用户对象
        payload = jwt_payload_handler(user)
        # JWTtoken
        token = jwt_encode_handler(payload)

        # 将token绑定到user,一并相应出去
        user.token = token

        # 响应数据
        return user